/**
 * @author harry
 * @date 2022/3/2/11:24
 */

package com.serviceOrchestration.atomic.units;

import com.serviceOrchestration.annotation.AtomicParam;
import com.serviceOrchestration.annotation.AtomicService;
import com.serviceOrchestration.atomic.AtomicUnit;
import com.serviceOrchestration.atomic.AtomicUnitContext;
import com.serviceOrchestration.pojo.User;
import com.serviceOrchestration.factory.AtomicFactory;
import com.serviceOrchestration.util.InputType;
import lombok.Getter;

import java.util.*;

@AtomicService(
        value = AtomicFactory.BEAN_PREFIX + 5,
        name = "地域购买控制服务",
        description = "检查用户所属地区是否在产品允许购买的范围内"
)
@Getter
public class RegionRestrictionUnit extends AtomicUnit {
    @AtomicParam(
            zhName = "允许的地区",
            enName = "areaAllowed",
            type = InputType.MULTI_SELECTION,
            repository = "areaDao.selectAll"
    )
    private final Set<String> areaAllowed = new HashSet<>();

    @SuppressWarnings("unchecked")
    @Override
    public void setParams(Map<String, Object> params) throws IllegalArgumentException {
        if(params == null) {
            throw new IllegalArgumentException("the params of RegionRestrictionUnit is null");
        }
        List<String> areas = (List<String>) params.get("areaAllowed");
        if(areas == null || areas.size() == 0) {
            throw new IllegalArgumentException("no param named 'areaAllowed'");
        }
        areaAllowed.addAll(areas);
    }

    @Override
    protected boolean doHandle(AtomicUnitContext context) {
        User user = (User) context.getContext("user");
        if (!areaAllowed.contains(user.getArea())) {
            context.setError("所在地区不允许");
            return false;
        }
        return true;
    }
}
